﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace WebApp.Models
{
    public class JsonBinder<T>: IModelBinder
    {

        public void TransformationObj(ModelBindingContext bindingContext)
        {
            //从请求中获取提交的参数数据 
            string json = bindingContext.HttpContext.Request.Form[bindingContext.ModelName];
            //提交参数是对象 
            if (json.StartsWith("{") && json.EndsWith("}"))
            {
                JObject jsonBody = JObject.Parse(json);
                JsonSerializer js = new JsonSerializer();
                object obj = js.Deserialize(jsonBody.CreateReader(), typeof(T));
                

                bindingContext.Result = ModelBindingResult.Success(obj);
            }
            //提交参数是数组 
            if (json.StartsWith("[") && json.EndsWith("]"))
            {
                IList<T> list = new List<T>();
                JArray jsonRsp = JArray.Parse(json);
                if (jsonRsp != null)
                {
                    for (int i = 0; i < jsonRsp.Count; i++)
                    {
                        JsonSerializer js = new JsonSerializer();
                        object obj = js.Deserialize(jsonRsp[i].CreateReader(), typeof(T));
                        list.Add((T)obj);
                    }
                }
                bindingContext.Result = ModelBindingResult.Success(list);
            }
        }


        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var t =Task.Run(() => { TransformationObj(bindingContext); });
            return t;
        }
    }
}
